package com.example.sprintbootsse.controller;

import com.example.sprintbootsse.dto.SendMegRequest;
import com.example.sprintbootsse.service.SseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("sse")
@ResponseBody
public class SseController {
    @Autowired
    private SseService sseServer;


    @GetMapping(value = "/subscribe/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter subscribe(@PathVariable("userId") String userId){
        return sseServer.connect(userId);
    }

    @GetMapping(value = "/batchSubscribe/{userIds}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public List<SseEmitter> batchSubscribe(@PathVariable("userIds") String userIds){
        List<SseEmitter> sseEmitters = new ArrayList<>();
        for(String userId : userIds.split(",")){
            sseEmitters.add(sseServer.connect(userId));
        }
        return sseEmitters;
    }


    @PostMapping(value = "/send/{userId}")
    public String sendMessage(@PathVariable("userId") String userId ,@RequestBody SendMegRequest sendMegRequest){
        if(sseServer.send(sendMegRequest.getUserId(), sendMegRequest.getSendMsg())){
            return "Success";
        }
        return "Faild";
    }

    @PostMapping(value = "/batchSendMessage")
    public String batchSendMessage(@RequestBody List<SendMegRequest> sendMegRequests){
        for (SendMegRequest sendMegRequest : sendMegRequests) {
            sseServer.send(sendMegRequest.getUserId(), sendMegRequest.getSendMsg());
        }
        return "Success";
    }

    @GetMapping(value = "/close/{userId}")
    public void close(@PathVariable("userId") String userId){
        sseServer.close(userId);
    }
}
